import { Card } from 'antd'
import { render } from 'react-dom'

import { createMinimalBrowserClient } from '@slardar/web'

import { TriggerEvent } from './event'
import { TriggerPageview } from './pageview'

const $root = document.querySelector('#app')

const Slardar = createMinimalBrowserClient()

const start = () => {
  Slardar.start()
}
const init = () => {
  Slardar('init', Cypress.env().config)
  Slardar('on', 'init', () => {
    Slardar?.getSender()?.setSize(0)
    Slardar?.getSender()?.setWait(0)
  })
}
const triggerCustomEvent = () => {
  Slardar('sendEvent', {
    name: 'custom-event',
    metrics: {
      a: 3,
    },
    categories: {
      b: '3',
    },
  })
}

const triggerCustomLog = () => {
  Slardar('sendLog', {
    content: 'custom-event',
    extra: {
      a: 3,
      b: '3',
    },
    level: 'error',
  })
}

const triggerCapture = () => {
  Slardar('captureException', new Error('manual captureException'), { extraKey: 'extra info' })
}

const triggerCaptureErrorEvent = () => {
  window.addEventListener('error', (e) => {
    Slardar('captureException', e)
  })
  const a = undefined
  // @ts-expect-error
  a.b()
}

const triggerCapturePromiseRejection = () => {
  window.addEventListener('unhandledrejection', (e) => {
    Slardar('captureException', e)
  })
  new Promise((_resolve, reject) => {
    reject('test')
  })
}

const App = () => {
  return (
    <div className="app">
      <Card>
        <h1>Slardar SDK</h1>
        <p>Testing by cypress</p>
        <button id="start" onClick={start}>
          Start
        </button>
        <button id="init" onClick={init}>
          Init
        </button>
        <TriggerEvent />
        <TriggerPageview />
        <button id="trigger-custom-event" onClick={triggerCustomEvent}>
          trigger-custom-event
        </button>
        <button id="trigger-custom-log" onClick={triggerCustomLog}>
          trigger-custom-log
        </button>
        <button id="trigger-capture" onClick={triggerCapture}>
          trigger-capture
        </button>
        <button id="trigger-capture-error-event" onClick={triggerCaptureErrorEvent}>
          trigger-capture-error-event
        </button>
        <button id="trigger-capture-promise-rejection" onClick={triggerCapturePromiseRejection}>
          trigger-capture-promise-rejection
        </button>
      </Card>
    </div>
  )
}

render(<App />, $root!)

const delay = new URL(location.href).searchParams.get('delay')
if (delay) {
  setTimeout(() => {
    Slardar('init', Cypress.env().config)
    Slardar('on', 'init', () => {
      Slardar?.getSender()?.setSize(0)
      Slardar?.getSender()?.setWait(0)
    })
  }, parseInt(delay))
} else {
  Slardar('init', Cypress.env().config)
  Slardar('on', 'init', () => {
    Slardar?.getSender()?.setSize(0)
    Slardar?.getSender()?.setWait(0)
  })
}
